package com.yf1706.configuration;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
public class FastJSONConfiguration {
	/*配置SpringMVC与FastJSON集成*/
	@Bean
	public FastJsonHttpMessageConverter convertFastJSON() {
		//创建FastJson信息转换对象 
		FastJsonHttpMessageConverter convert=new FastJsonHttpMessageConverter();
		
		//设定序列化规则
		List<MediaType> supportedMediaTypes=new ArrayList<MediaType>();
		supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		supportedMediaTypes.add(MediaType.TEXT_HTML);
		//规则赋予转换对象
		convert.setSupportedMediaTypes(supportedMediaTypes);
		//创建Fastjosn对象
		FastJsonConfig fastJsonConfig=new FastJsonConfig();
//		输出key时是否使用双引号,默认为true
		fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames);
//		避免默认的循环引用替换
		fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect);
//		是否输出值为null的字段 ,默认是false
		fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
//		字符类型字段如果为null,输出为"",而非null
		fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty);
//		数值字段如果为null,输出为0,而非null
		fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullNumberAsZero);
//		Boolean字段如果为null,输出为false,而非nul
		fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullBooleanAsFalse);
//		List字段如果为null,输出为[],而非null
		fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty);
//		Date的日期转换器
		fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteDateUseDateFormat);
		convert.setFastJsonConfig(fastJsonConfig);
		convert.setDefaultCharset(Charset.forName("UTF-8"));
		return convert;
	}
}
